import { calculateStockPath, JOIN_KEY } from './skuManager';

const toJson = (str) => {
  if (typeof str === 'string') {
    return JSON.parse(str);
  }

  return str;
};

const getSelectedOptions = (curProduct) => {
  let defaultSel = [];
  let option = curProduct?.option || curProduct?.optionValue;

  if (!option) {
    return {
      defaultSel,
      isWithOption: false,
    };
  }

  option = toJson(option);

  for (let key in option) {
    defaultSel.push({ name: key, value: option[key] });
  }

  return {
    defaultSel,
    isWithOption: !!defaultSel.length,
  };
};

function checkIsSold(stockPath, selectedOptions) {
  const path = selectedOptions
    .map(({ name, value }) => {
      return `${name}${JOIN_KEY}${value}`;
    })
    .sort((v1, v2) => {
      return v1.localeCompare(v2);
    })
    .join(JOIN_KEY);

  return stockPath[path] === 0;
}

function getDefaultOptions(productDetail, curProduct) {
  const { stockPath, optionList } = calculateStockPath(
    productDetail.options,
    productDetail.noStockOptions,
  );

  let defaultSel = [];
  let isWithOption = false;
  let isWithOptionSold = false;

  // 获取 其它页面跳转过来的数据
  ({ defaultSel, isWithOption } = getSelectedOptions(curProduct));

  // 判断 这条路径是否 没有规格了
  if (isWithOption) {
    const isSold = checkIsSold(stockPath, defaultSel);

    if (isSold) {
      isWithOption = false;
      isWithOptionSold = defaultSel;
      defaultSel = [];
    }
  }

  // 选择一条默认路径
  if (!isWithOption) {
    if (optionList.length === 1) {
      defaultSel = optionList[0];
    }
  }

  // TODO:  Object.keys()和for in 具有相同的排列顺序
  // 如果属性名的类型是Number，那么Object.keys返回值是按照key从小到大排序
  // 如果属性名的类型是String或Symbol，那么Object.keys返回值是按照属性被创建的时间升序排序，且一定排在Number之后
  // https://www.cnblogs.com/dirgo/p/9952927.html
  // 处理 defaultSel 的顺序问题
  if (Object.keys(defaultSel).length > 0) {
    defaultSel = Object.keys(toJson(productDetail.options)).map((name) => {
      const item = defaultSel.find(({ name: dName }) => {
        return dName === name;
      });

      return {
        name,
        value: item.value,
      };
    });
  }

  return {
    product: productDetail,

    isNeedChoice: optionList.length > 1,
    defaultSel,
    isWithOption,
    isWithOptionSold,

    stockPath,
    optionList,
  };
}

function checkProductIsSoldOut(product = {}, key = 'inventoryQuantity') {
  let v;

  // 如果是字符串或者数字, 直接赋值
  if (typeof product !== 'object') {
    v = product;
  } else {
    v = product[key];
  }

  // 如果状态未返回
  if (v === undefined || v === null) {
    return false;
  }

  // 可能为字符串
  return parseInt(`${v}`, 10) <= 0;
}

export { getDefaultOptions, checkIsSold, checkProductIsSoldOut };
